package com.ylcode.libback.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylcode.libback.common.R;
import com.ylcode.libback.model.pojo.Employee;
import com.ylcode.libback.service.EmployeeService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;

    /**
     * 员工登录
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("账号不存在");
        }
        //比对密码，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误");
        }
        //查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }
        //登录成功，将员工id存入如session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前登录员工的id
        log.info("id:"+request.getSession().getAttribute("employee")+"退出登录");
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 查询员工总数
     */
    @GetMapping("/total")
    public R<Long> total() {
        long total = employeeService.count();
        log.info("总数" + total);
        return R.success(total);
    }

    /**
     * 员工信息分页查询
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //创建分页插件
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, lambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 查询所有员工
     */
    @GetMapping
    public R<List<Employee>> queryAll() {
        List<Employee> empList = employeeService.list();
        return R.success(empList);
    }

    /**
     * 新增员工
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //设置初始密码123456，需要进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //太繁琐,使用MP的字段自动填充优化
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获取当前登录用户的id
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 根据ID查询员工
     */
    @GetMapping("/{id}")
    public R<Employee> getEmpById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("出错了");
    }

    /**
     * 根据ID删除员工
     */
    @DeleteMapping("/{id}")
    public R<String> del(@PathVariable Long id) {
        boolean flag = employeeService.removeById(id);
        if (!flag) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    /**
     * 根据姓名or账号查询员工
     */
    @GetMapping("/getEmpByNameOrUsername")
    public R<List<Employee>> getEmpByNameOrUsername(String param) {
        List<Employee> employees = employeeService.queryEmpByNameOrUsername(param);
        return R.success(employees);
    }

    @GetMapping("/forbid/{id}")
    public R<String> forbid(@PathVariable String id) {
        long empId = Long.parseLong(id);
        Employee employee = employeeService.getById(empId);
        Integer status = employee.getStatus();
        if (status == 1) {
            employee.setStatus(0);
            boolean flag = employeeService.updateById(employee);
            if (flag) {
                return R.success("已禁用");
            }
        }
        employee.setStatus(1);
        boolean flag = employeeService.updateById(employee);
        if (flag) {
            return R.success("已启用");
        }
        return R.error("出错了");
    }
}
